package liudan.archetype.xmlutil;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * Title
 * Copyright: Copyright (c) 2017
 * User: liudan
 * Created on 2017/2/18 10:49
 */
public class StrutsXmlParser {

    /***
     * 解析xml
     * @param xmlPath
     * @return
     */
    public static Map<String, XmlBean> parser(String xmlPath) {
        Map<String, XmlBean> xmlBeanMap = new HashMap<String, XmlBean>();
        try {
            SAXBuilder builder = new SAXBuilder();
            Document jdocument = builder.build(new File(xmlPath));
            Element root = jdocument.getRootElement();
            Element actionMapping = root.getChild("action-mapping");
            List<Element> action = actionMapping.getChildren("action");
            for (Element s : action) {
                XmlBean xmlBean = new XmlBean();
                String name = s.getAttributeValue("name");
                String formClass = "";
                String path = "";
                path = s.getAttributeValue("path");
                String type = s.getAttributeValue("type");
                xmlBean.setBeanName(name);
                xmlBean.setPath(path);
                xmlBean.setActionType(type);

                Element formbean = root.getChild("formbeans");
                List<Element> formbeans = formbean.getChildren();
                for (Element form : formbeans) {
                    if (name.equals(form.getAttributeValue("name"))) {
                        formClass = form.getAttributeValue("class");
                        break;
                    }
                }
                xmlBean.setFormclass(formClass);
                List<Element> forward = s.getChildren();
                Map<String, String> fmap = new HashMap<String, String>();
                for (Element fo : forward) {
                    String fname = fo.getAttributeValue("name");
                    String fvalue = fo.getAttributeValue("value");
                    fmap.put(fname, fvalue);
                }
                xmlBean.setForwardMap(fmap);
                xmlBeanMap.put(path, xmlBean);
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xmlBeanMap;
    }

}
